import sortedcontainers
class Solution(object):
    def numTeams(self, rating):
        n = len(rating)
        l_lower = [0] * n
        r_lower = [0] * n
        st = sortedcontainers.SortedList()
        for i in range(n):
            index = st.bisect_left(rating[i])
            l_lower[i] = index
            st.add(rating[i])
        st = sortedcontainers.SortedList()
        for i in range(n - 1, -1, -1):
            index = st.bisect_left(rating[i])
            r_lower[i] = index
            st.add(rating[i])
        ans = 0
        for i in range(1, n - 1):
            ans += l_lower[i] * (n - 1 - i - r_lower[i]) + r_lower[i] * (i - l_lower[i])
        return ans